package com.boco.pciv.controller;

import com.boco.pciv.core.controller.BaseController;
import com.boco.pciv.core.security.LoginUser;
import com.boco.pciv.entity.sys.UserLogInfo;
import com.boco.pciv.service.shiro.ShiroUtils;
import cn.hutool.core.util.StrUtil;
import com.boco.pciv.service.sys.IUserLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.io.Serializable;

/**
 * Created by CC on 2017/9/4.
 * 基础控制器
 */
public class PcivController extends BaseController {
    private  static Logger log = LoggerFactory.getLogger(PcivController.class);
    @Resource
    private IUserLogService logSer;

    @Override
    protected LoginUser getCurUser() {
        return ShiroUtils.getUserEntity();
    }

    @Override
    protected String getCurUserId() {
        return ShiroUtils.getUserId();
    }

    @Override
    protected Boolean checkUserLogin() {
         return ShiroUtils.isLogin();
    }

    @Override
    protected void setSessionData(String key, Serializable value) {
        ShiroUtils.setSessionAttribute(key,value);
    }

    @Override
    protected Object getSessionData(String key) {
        return ShiroUtils.getSessionAttribute(key);
    }

    @Override
    protected String getSessionId() {
        return ShiroUtils.getSession().getId().toString();
    }

    /**
     * 记录操作日志
     * @param action 方法
     * @param logInfo 日志信息
     */
    protected void addOperationLog(String action, String logInfo){
        addOperationLog(getCurModelId(),action,logInfo);
    }

    /**
     * 记录操作日志
     * @param ModuleId 模块id
     * @param action 操作
     * @param logInfo 日志信息
     */
    protected void addOperationLog(String ModuleId, String action, String logInfo){
        UserLogInfo loginfo = new UserLogInfo();
        loginfo.setUserId(getCurUserId());
        loginfo.setLogType(1);
        loginfo.setAction(action);
        loginfo.setInfo(logInfo);
        loginfo.setModuleId(ModuleId);
        loginfo.setUserIp(getUserIp());
        try{
            logSer.add(loginfo);
        }
        catch (Exception ex)
        {
            log.warn("日志记录失败",ex);
        }
    }

    /**
     * 添加登录日志
     */
    protected void addLoginLog() {
        UserLogInfo loginfo = new UserLogInfo();
        String uid = getCurUserId();
        if(StrUtil.isBlank(uid)){
            return;
        }
        loginfo.setUserId(uid);
        loginfo.setLogType(2);
        loginfo.setAction("系统登录");
        loginfo.setInfo("用户"+uid+"登录");
        loginfo.setModuleId("");
        loginfo.setUserIp(getUserIp());
        try{
            logSer.add(loginfo);
        }
        catch (Exception ex) {
            log.warn("日志记录失败",ex);
        }
    }
}
